import type { questionComponentStoreType, questionComponentType } from "@/utils/type"
import { type StateCreator } from 'zustand';
import { produce } from 'immer';
import { arrayMove } from '@dnd-kit/sortable'




export const componentStore: StateCreator<questionComponentStoreType> = (set) => (
  {
    componentList: [],
    setComponentList: (componentList: questionComponentType[]) => set(() => ({ componentList })),
    addComponent: (component: questionComponentType,selectedId:string) =>
      set(produce((state) => {
        const index = state.componentList.findIndex((item: questionComponentType) => item.fe_id === selectedId);
        if (index < 0) {
          state.componentList.push(component);
        } else {
          state.componentList.splice(index + 1, 0, component);
        }
      })),
    updateComponent: (component: questionComponentType) =>
      set(produce(state => {
        const index = state.componentList.findIndex((item: questionComponentType) => item.fe_id === component.fe_id);
        if (index >= 0) {
          state.componentList[index] = component; // Immer 会处理不可变性
        }
      })),
    deleteComponent: (componentId: string) =>
      set(produce((state) => {
        const index = state.componentList.findIndex((item: questionComponentType) => item.fe_id === componentId);
        if (index < 0) return;
        // state.selectedId = selectNextId(componentId, state.componentList);
        state.componentList.splice(index, 1);
      })),
    hiddenComponent: (componentId: string) =>
      set(produce((state) => {
        const index = state.componentList.findIndex((item: questionComponentType) => item.fe_id === componentId);
        if (index < 0) return;
        state.componentList[index].isHidden = !state.componentList[index].isHidden;
      })),
    lockComponent: (componentId: string) =>
      set(produce(state => {
        const index = state.componentList.findIndex((item: questionComponentType) => item.fe_id === componentId)
        if (index < 0) return
        state.componentList[index].isLocked = !state.componentList[index].isLocked
      })),
    moveComponent: (oldIndex: number, newIndex: number) =>
      set(produce(state => {
        const newList = arrayMove(state.componentList, oldIndex, newIndex)
        state.componentList = newList
      })),
    updateTitle: (title: string, id: string) =>
      set(produce(state => {
        const index = state.componentList.findIndex((item: questionComponentType) => item.fe_id === id)
        if (index < 0) return
        state.componentList[index].title = title

      }))

  }
)